<template>
  <div class="create-component-list">
    <a-flex vertical align="center">
      <div v-for="(item, index) in defaultTextTemplates"
      :key="index" class="create-component-list-item"
      @click="addClick(item)"
      @mouseenter.stop="mouseEnter({row: item, elementId: `component-list-item_${index}`})"
      :style="{height: item.height}"
      >
        <z-text draggable="true" :id="`component-list-item_${index}`" :contenteditable="false"  v-bind="item" ></z-text>
      </div>
    </a-flex>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import getDefaultTextTemplates from '../../defaultTextTemplates'
import { PartialTextComponentProps } from '../../hooks/useComponentCommon'
import useTheme from '../../stores/module/theme'
const { themeColor } = storeToRefs(useTheme())

const defaultTextTemplates = ref<PartialTextComponentProps[]>(getDefaultTextTemplates(themeColor.value))

watch(() => themeColor.value, (newVal) => {
  // console.log(1111, newVal)
  defaultTextTemplates.value = getDefaultTextTemplates(newVal)
})

const emit = defineEmits(['addItem'])

const addClick = (row: PartialTextComponentProps) => {
  emit('addItem', row)
}

// 鼠标拖拽结束
const mouseEnter = (data: {row: PartialTextComponentProps, elementId: string}) => {
  const { row, elementId } = data
  const element = document.getElementById(elementId) as HTMLDListElement
  console.log(111, element.clientHeight)
  mouseStartDrop({...row, height: element.clientHeight + 22 + 'px', width: element.clientWidth + 22 + 'px'})
}

// 鼠标拖拽 给画布添加元素
const mouseStartDrop = (enterComponent: PartialTextComponentProps) => {
  const editorContainer = document.getElementById('editorContainer') as HTMLDivElement
  const canvasArea = document.getElementById('canvas-area') as HTMLDivElement

  let width: number, height: number
  editorContainer.ondragstart = (e) => {
    const ele = e.target as HTMLElement
    width = ele.clientWidth
    height = ele.clientHeight
    console.log('start', ele.clientWidth)
  }

  editorContainer.ondragover = (e) => {
    e.preventDefault()
    // console.log('over', e.target)
  }

  editorContainer.ondrop = (e) => {
    // const ele = e.target as HTMLElement
    const { left, top } = canvasArea.getBoundingClientRect()
    const leftL = e.clientX - left - width / 2 + 'px'
    const topL = e.clientY - top- height / 2 + 'px'
    
    emit('addItem', {
      ...enterComponent, left: leftL, top: topL
    })
  }
}

// defineExpose({
//   defaultTextTemplates
// })
</script>

<style lang="scss" scoped>

.create-component-list {
  
  &-item {
    cursor: pointer;
    // width: 100%;
    margin-bottom: 12px;
    position: relative;
    height: auto;
  }
}
</style>